import re
import urllib

from google.appengine.ext import db

from waveapi import events
from waveapi import model
from waveapi import robot

import kinds

link_re = re.compile(r'\b(?:(?:https?|ftp)://|www\.|ftp\.)(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#/%=~_|$?!:,.]*\)|[A-Z0-9+&@#/%=~_|$])',re.IGNORECASE)


def update_blip_links(blip_id,links,wave):
	old_links = db.Query(kinds.Link)
	old_links.filter('blip_id =',blip_id)
	old_links.ancestor(wave)
	db.delete(old_links)
	db.put(links)

def scan_blip(blip,wave):
	new_links = []
	text = blip.GetDocument().GetText()
	new_links = []
	blip_id = blip.GetId()
	wave_id = wave.wave_id
	for url in link_re.finditer(text):
		link = kinds.Link(parent=wave,url=url.group(0),blip_id=blip_id,wave_id=wave_id)
		new_links.append(link)
	return new_links

def OnBlipSubmitted(properties, context):
	root_wavelet = context.GetRootWavelet()
	blip_id = properties['blipId']
	blip = context.GetBlipById(blip_id)
	wave_id = root_wavelet.GetWaveId()
	wave = kinds.Wave.get_by_key_name(wave_id)

	new_links = scan_blip(blip,wave)
	db.run_in_transaction(update_blip_links,blip_id,new_links,wave)

def OnBlipDeleted(properties, context):
	root_wavelet = context.GetRootWavelet()
	blip_id = properties['blipId']
	wave_id = root_wavelet.GetWaveId()

	old_links = db.Query(kinds.Link)
	old_links.filter('blip_id =',blip_id)
	old_links.ancestor(wave)
	db.delete(old_links)

def OnRobotAdded(properties, context):
	wave_id = context.GetRootWavelet().GetWaveId()
	kinds.Wave.get_or_insert(wave_id, wave_id = wave_id)
	wave = kinds.Wave.get_by_key_name(wave_id)

	for blip in context.GetBlips():
		new_links = scan_blip(blip,wave)
		db.run_in_transaction(update_blip_links,blip.GetId(),new_links,wave)

	context.GetRootWavelet().CreateBlip().GetDocument().SetText("Hey there! You can see all the URLs mentioned here at http://linkywave.appspot.com/links/?wave_id=%s"%urllib.quote(wave_id))

if __name__ == '__main__':
	myRobot = robot.Robot('linkywave', image_url='http://linkywave.appspot.com/icon.png', version='3', profile_url='http://linkywave.appspot.com/')
	myRobot.RegisterHandler(events.BLIP_SUBMITTED, OnBlipSubmitted)
	myRobot.RegisterHandler(events.WAVELET_SELF_ADDED, OnRobotAdded)
	myRobot.RegisterHandler(events.BLIP_DELETED, OnBlipDeleted)
	myRobot.Run()
